﻿using System;
using System.Diagnostics.Contracts;
using System.Linq;
using IMModel.Domain.Common;
using System.Collections.Generic;

namespace IMModel.Domain
{
    /// <summary>
    /// Определяет категорию в разделе в определённом периоде
    /// </summary>
    public partial class CategorySectionTerm : IRespondentIndexVector, ICacheble, IItem
    {
        private RespondentIndexCollection _respondentIndexCollection;
        private Dictionary<IndexContext, RespondentIndexCollection> _respondentIndexCaches;

        public void Invalidate()
        {
            Contract.Ensures(_respondentIndexCollection == null);
            Contract.Ensures(_totalWeight == null);

            _respondentIndexCollection = null;
            _totalWeight = null;

            CharacteristicTerms.Invalidate();
        }

        public RespondentIndexCollection Indexes
        {
            get
            {
                return CalcIndexes(IndexContext.Current);
                //return _respondentIndexCollection;
            }
        }

        /// <summary>
        /// Получает индекс заданного респондента
        /// </summary>
        /// <param name="respondent"></param>
        /// <returns></returns>
        public double this[Respondent respondent]
        {
            get
            {
                Contract.Requires(Indexes != null);
                Contract.Requires(respondent != null);

                return Indexes[respondent];
            }
        }

        //private void CalcIndexes()
        //{
        //    if (_respondentIndexCollection != null) return;
        //    _respondentIndexCollection = RespondentIndexCollectionProvider
        //        .GetCollectors(this).GetIndexes(x => x.GetNormalizedWeight());
        //}

        /// <summary>
        /// выборка по Characteristic и расчёт индексов в соответствие с выбранной политикой
        /// </summary>
        public RespondentIndexCollection CalcIndexes(IndexContext сontext)
        {
            return CCache.Get(ref _respondentIndexCaches, сontext,
                () => RespondentIndexCollectionProvider.GetCollectors(this)
                .Where(x => сontext.IndexObjectFilter(x.Characteristic))
                .GetIndexes(сontext, x => x.GetNormalizedWeight()));
        }

        public override string ToString()
        {
            return string.Format("{0} ({1}-{2}): {3}-{4}",
                this.SectionTerm.Term.Organization.Name,
                this.SectionTerm.Term.Start.Year,
                this.SectionTerm.Term.Stop.Year,
                this.SectionTerm.Section.Name,
                this.CategoryTerm.Category.Name);
        }
    }
}